package com.flx.controller;


import com.flx.anno.OperateLog;
import com.flx.service.LoginService;
import dto.LoginDto;
import entity.Login;
import exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import utils.JwtUtil;
import vo.Result;

import java.util.HashMap;
import java.util.Map;

/**
 * (Login)表控制层
 *
 * @author makejava
 * @since 2025-04-22 08:52:32
 */
@RestController
@RequestMapping
public class LoginController {
  @Autowired
  private LoginService loginService;

  @GetMapping("/login")
  public Result userLogin(Login login) throws CustomException {
      String userName = login.getUserName();
      String aliasName = login.getAliasName();
      // 获取用户登录令牌
      Map<String, Object> claims = new HashMap<>();
      claims.put("userName", userName);
      claims.put("aliasName", aliasName);
      String token = JwtUtil.createToken(claims);

      Login userLogin = loginService.userLogin(login);
      LoginDto loginDto = LoginDto.builder()
              .id(userLogin.getId())
              .userName(userLogin.getUserName())
              .aliasName(userLogin.getAliasName())
              .token(token)
              .build();

      return Result.success(loginDto, "登录成功");

  }

  @PostMapping("/add")
  public Result add(@RequestBody Login login) {
      loginService.insertUser(login);
      return Result.success("添加成功");
  }

  @DeleteMapping("/del/{userName}")
  public Result del(@PathVariable String userName) {
      boolean delUser = loginService.delUser(userName);
      if (delUser) {
          return Result.success("删除成功");
      } else {
          return Result.error("删除失败");
      }
  }
}

